//
//  RHChoiceDeviceTypeView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/3.
//

#import "RHChoiceDeviceTypeView.h"
#import "RHWindowTipManage.h"
#import "UIView+Extension.h"
#import "RHEndPointModel.h"
#import "RHChoiceDevTypeCell.h"
#import "RHTools.h"

@interface RHChoiceDeviceTypeView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UIView *contentView;

@property (nonatomic ,strong) UITableView *left_tableView;

@property (nonatomic ,strong) UITableView *right_tableView;

@property (nonatomic ,strong) MASConstraint *bgViewTopConstraint;

@property (nonatomic ,strong) MASConstraint *bgViewBottomConstraint;

@property (nonatomic ,assign) NSInteger selectIndex;

@property (nonatomic, strong) NSMutableArray *selectTypes;//保存的是字符串
@end

@implementation RHChoiceDeviceTypeView

-(instancetype)init
{
    if(self = [super init]){
        [self setupUI];
    }
    return self;
}
- (void)setPlantTypeList:(NSArray<RHDevTypeModel *> *)plantTypeList
{
    _plantTypeList = plantTypeList;
    [self.left_tableView reloadData];
    
    //默认选中第一个
    if(plantTypeList.count>0){
    
        RHDevTypeModel *model = [plantTypeList firstObject];
        model.isSelected = YES;
//        if(model.types.count>0){
//            self.curModel = [model.types firstObject];
//        }

    }
}

-(void)setCurTypes:(NSArray *)curTypes
{
    self.selectTypes = [NSMutableArray arrayWithArray:curTypes];
    [self.plantTypeList enumerateObjectsUsingBlock:^(RHDevTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.types enumerateObjectsUsingBlock:^(RHDevTypeModel*  _Nonnull subType, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([self.selectTypes containsObject:subType.plantType]) {
                subType.isSelected = YES;
            }
        }];
            
    }];
    [self.right_tableView reloadData];
}

- (void)setupUI{
    kWeakSelf;
    self.selectTypes = [NSMutableArray array];
    [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
    
    UIView *touchView = [[UIView alloc] init];
    [touchView setBackgroundColor:UIColor.clearColor];
    [self addSubview:touchView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    touchView.userInteractionEnabled = YES;
    [touchView addGestureRecognizer:tap];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    [self addSubview:contentView];
    self.contentView = contentView;
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        
    }];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setText:@"请选择设备类型".rh_localized];
    _titleLab.numberOfLines = 0;
    [_titleLab setTextAlignment:NSTextAlignmentCenter];
    [_titleLab setFont:[UIFont systemFontOfSize:16]];
    [_titleLab setTextColor:FontColor(@"#969799")];
    _titleLab.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:_titleLab];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(15);
    [sureBtn setTitleColor:CMainColorGreen forState:UIControlStateNormal];
    [contentView addSubview:sureBtn];
    
    _left_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_left_tableView setSeparatorColor:FontColor(@"#F5F5F5")];
    [_left_tableView setBackgroundColor:CFTabViewBgColor];
    [_left_tableView setDelegate:self];
    [_left_tableView setDataSource:self];
    [_left_tableView registerClass:[RHChoiceDevTypeCell class] forCellReuseIdentifier:@"RHChoiceDevTypeCell_left"];
    [contentView addSubview:_left_tableView];
    
    _right_tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_right_tableView setSeparatorColor:FontColor(@"#F5F5F5")];
    [_right_tableView setBackgroundColor:UIColor.whiteColor];
    [_right_tableView setDelegate:self];
    [_right_tableView setDataSource:self];
    [_right_tableView registerClass:[RHChoiceDevTypeCell class] forCellReuseIdentifier:@"RHChoiceDevTypeCell_right"];
    [contentView addSubview:_right_tableView];
    
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:FontColor(@"#eeeeee")];
    [contentView addSubview:lineV];
    
    UIView *bottomView = kView;
    bottomView.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.height.offset(-kSafe_bottom);
    }];
    
  
    [touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    
    CGFloat btnWidth =  [sureBtn.titleLabel.text getStringWidthFont:sureBtn.titleLabel.font limitHeight:20];
    CGFloat titleWidth = (kUI_WINDOW_W - (30 + btnWidth)*2);
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.height.mas_equalTo(49);
        make.top.mas_offset(0);
        make.width.offset(titleWidth);
    }];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.titleLab);
        make.right.mas_offset(-15);
        make.height.offset(40);
    }];
    
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(1);
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
    }];
    
    [_left_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
        make.left.mas_offset(0);
        make.bottom.equalTo(bottomView.mas_top);
        make.height.offset(200);
        make.width.offset(kUI_WINDOW_W/2);
    }];
    [_right_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(weakSelf.left_tableView);
        make.left.equalTo(weakSelf.left_tableView.mas_right).offset(0);
    }];
  
    
    contentView.layer.cornerRadius = 8;
    contentView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    
    [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        if (weakSelf.choiceResultBlock) {
            weakSelf.choiceResultBlock(nil);
        }
        [weakSelf hidden];
    }];
    
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
//        if(weakSelf.curModel){
            if (weakSelf.choiceResultBlock) {
                weakSelf.choiceResultBlock(weakSelf.selectTypes);
            }
            [weakSelf hidden];
//        }
    }];

}




//首次进入的时候滚动到当前值所在列
-(void)scorllToCurrentValue
{
    
    __block  NSInteger component = 0;
    __block  NSInteger row = 0;
    
//    [self.plantTypeList enumerateObjectsUsingBlock:^(RHDevTypeModel * _Nonnull typeModel, NSUInteger typeIdx, BOOL * _Nonnull stop) {
//        [typeModel.types enumerateObjectsUsingBlock:^(RHDevTypeModel*  _Nonnull subType, NSUInteger idx, BOOL * _Nonnull stop) {
//            if([subType.plantType isEqualToString:_curModel.plantType]){
//                component = typeIdx;
//                row = idx;
//            }
//        }];
//    }];

   
        
    
    
   
}

- (void)hidden{
    kWeakSelf;
    [self.bgViewBottomConstraint uninstall];
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        
    }];
    [UIView animateWithDuration:0.2 animations:^{
        [self setNeedsLayout];
        [self layoutIfNeeded];
        [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
}


- (void)showAnimation{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    self.frame = [UIApplication sharedApplication].keyWindow.bounds;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgViewTopConstraint uninstall];
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            self.bgViewBottomConstraint = make.bottom.mas_offset(0);
            
        }];
        [UIView animateWithDuration:0.2 animations:^{
            [self setNeedsLayout];
            [self layoutIfNeeded];
            [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.3]];
        }];
    });
    
}



- (void)hiddenAnimation{
    
    
}



#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.left_tableView]) {
        return _plantTypeList.count;
    }else{
        RHDevTypeModel *model = [self.plantTypeList safeObjectAtIndex:self.selectIndex];
        return model.types.count;;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.left_tableView]) {
        RHChoiceDevTypeCell *leftCell = [tableView dequeueReusableCellWithIdentifier:@"RHChoiceDevTypeCell_left"];
        RHDevTypeModel *model = [self.plantTypeList safeObjectAtIndex:indexPath.row];
        [leftCell setTypeModel:model];
        return leftCell;
    }else{
        RHDevTypeModel *model = self.plantTypeList[self.selectIndex];
        RHDevTypeModel *subModel = [model.types safeObjectAtIndex:indexPath.row];
        RHChoiceDevTypeCell *rightCell = [tableView dequeueReusableCellWithIdentifier:@"RHChoiceDevTypeCell_right"];
        [rightCell setTypeModel:subModel];
        return rightCell;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.left_tableView]) {
        for (RHDevTypeModel *typeModel in self.plantTypeList) {
            typeModel.isSelected = NO;
        }
        self.selectIndex = indexPath.row;
        RHDevTypeModel *typeModel = [self.plantTypeList safeObjectAtIndex:indexPath.row];
        typeModel.isSelected = YES;
        [tableView reloadData];
        [self.right_tableView reloadData];
    }else{
        RHDevTypeModel *typeModel = [self.plantTypeList safeObjectAtIndex:self.selectIndex];
        RHDevTypeModel *subModel = [typeModel.types safeObjectAtIndex:indexPath.row];
        subModel.isSelected = !subModel.isSelected;
        [tableView reloadData];
        
        if (subModel.isSelected) {
            if (![self.selectTypes containsObject:subModel.plantType]) {
                [self.selectTypes addObject:subModel.plantType];
            }
        }else{
            [self.selectTypes removeObject:subModel.plantType];
        }
    }
}



-(void)dealloc{
    NSLog(@"---->ChoicePlantTypeView dealloc");
}


@end
